﻿$(function () {
    var right1 = Math.max.apply(null, $('line').map(function () { return parseFloat($(this).attr('x1')); }).get());
    var right2 = Math.max.apply(null, $('line').map(function () { return parseFloat($(this).attr('x2')); }).get());
    var right = right1 > right2 ? right1 : right2;
    var inside = false;
    $("g rect").each(function () {
        var cloned = $(this).clone().removeAttr('id').css('fill', 'none').attr('class', 'selected');
        if (parseFloat($(cloned).attr('x')) < right) {

            $(this).mouseenter(function () {
                addHighlight($(this), true);
            }).mouseleave(function () {
                $("g rect[class='selected']").remove();
            });
        }
        else {
            var self = $(this);
            $(this).nextAll("text").first().mouseenter(function (e) {
                if (!inside) {
                    inside = true;
                    $(self).trigger(e.type);
                }
            }).mouseleave(function (e) {
                $(self).trigger(e.type);
                inside = false;
            });
            $(this).mouseenter(function () {
                var group = $(this).attr('g');
                console.log(group);
                $("g rect[g='" + group + "']").each(function () {
                    if ($(this).css('fill') !== 'none') {
                        addHighlight($(this));
                    }
                });
            }).mouseleave(function () {
                $("rect[class='selected']").remove();
            });
        }
    });

    function addHighlight(element) {
        if ($(element).next().hasClass('selected') || $(element).attr('id') === undefined) {
            return;
        }
        var cloned = $(element).clone().removeAttr('id').removeAttr('opacity').css('fill', 'none').attr('class', 'selected');
        var width = parseFloat(cloned.attr('width'));
        var height = parseFloat(cloned.attr('height'));
        var x = parseFloat(cloned.attr('x'));
        var y = parseFloat(cloned.attr('y'));
        var opacity = ["0.3", "0.15", "0.05"];

        cloned.css('stroke', '#000000');
        cloned.css('stroke-width', 1);

        for (var i = 0; i < opacity.length; i++) {
            cloned = $(cloned).clone();
            cloned.attr('x', x - 1 - i);
            cloned.attr('y', y - 1 - i);
            cloned.css('opacity', 1);
            cloned.attr('width', width + 2 + i * 2);
            cloned.attr('height', height + 2 + i * 2);
            cloned.css('stroke-opacity', opacity[i]);
            cloned.insertAfter($(element));
        }
    }
});